package com.xcms.news;

import com.xcms.util.JDBCHelper;
import com.xcms.util.Page;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class NewsServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action=request.getParameter("action");
        if("add".equals(action)){
            String title = request.getParameter("title");
            News news=new News();
            news.setTitle(title);
            if(NewsDao.insert(news)){//如果添加成功要更新content里面的LatestNews
                ServletContext context = this.getServletContext();
                List<News> newsList=NewsDao.getLatestNews();
                context.setAttribute("LatestNews",newsList);
            }
            response.sendRedirect("/xcms/news?action=page&currPage=1");
        }
        if("delete".equals(action)){
            int id= Integer.parseInt(request.getParameter("id"));
            NewsDao.delete(id);
            ServletContext context = this.getServletContext();
            List<News> newsList=NewsDao.getLatestNews();
            context.setAttribute("LatestNews",newsList);
            response.sendRedirect("/xcms/news?action=page&currPage=1");

        }
        if("edit".equals(action)){
            int id= Integer.parseInt(request.getParameter("id"));
            String title= request.getParameter("title");
            ServletContext context = this.getServletContext();
            context.setAttribute("id",id);
            context.setAttribute("title",title);
//            title=request.getParameter("title");
//            title= String.valueOf(context.getAttribute("title"));
//
//            NewsDao.update(id,title);
//            response.sendRedirect("/xcms/edit.jsp");
            request.getRequestDispatcher("/edit.jsp").forward(request,response);

        }
        if("page".equals(action)){
            int currPage=Integer.parseInt(request.getParameter("currPage"));
            Page<News> page=NewsDao.getPage(10,currPage);
            request.setAttribute("page",page);
            request.getRequestDispatcher("finalmanagement.jsp").forward(request,response);
        }
    }
}
